package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.plugin2.message.Message;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/7/22 17:43
 * @Description:
 */
@RestController
@RequestMapping("/report")
public class ReportController {

	@Reference
	MemberService memberService;

	@Reference
	SetmealService setmealService;

	@Reference
	ReportService reportService;


	@RequestMapping("/getMemberReport")
	public Result getMemberReport() {
		try {
			Map map = new HashMap();
			List<String> months = new ArrayList();
			// 计算月份
			LocalDate startDate = LocalDate.now().minusMonths(12);
			for (int i = 0; i < 12 ; i++) {
				LocalDate tempDate = startDate.plusMonths(i);
				String s = tempDate.toString().substring(0, 7);
				months.add(s);
			}
			// 查询月份对应的会员数，访问数据库
			List<Integer> counts = memberService.findCountByMonth(months);

            map.put("months",months);
            map.put("memberCount",counts);
			return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
		} catch (Exception e){
			e.printStackTrace();
			return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
		}
	}
	
	/**
	 *  @描述：获取套餐占比数据
	 */
	@RequestMapping("/getSetmealReport")
	public Result getSetmealReport() {
		Map map = new HashMap();
		List<String> setmealNames= new ArrayList<>();
		List<Map> setmealCount = new ArrayList<>();
        //  查询setmealCount
		setmealCount = setmealService.findSetmealCount();

		// 根据setmealCount生成setmealNames
		if(!CollectionUtils.isEmpty(setmealCount)){
			setmealCount.forEach(item->{
				setmealNames.add(String.valueOf(item.get("name")));
			});
		}

        map.put("setmealNames", setmealNames);
		map.put("setmealCount", setmealCount);
		return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
	}

	@RequestMapping("/getBusinessReportData")
	public Result getBusinessReportData() {
		try {
			Map<String, Object> map = reportService.getBusinessReportData();
			return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
		} catch (Exception e){
			e.printStackTrace();
			return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
		}
	}
	
	/**
	 *  @描述：导出运营数据
	 */
	@RequestMapping("/exportBusinessReport")
	public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response)  {
		// 获取数据
		Map<String, Object> map = reportService.getBusinessReportData();
		String reportDate=	String.valueOf(map.get("reportDate"));
		Integer todayNewMember= Integer.parseInt(map.get("todayNewMember").toString());
		Integer totalMember= Integer.parseInt(map.get("totalMember").toString());
		Integer thisWeekNewMember= Integer.parseInt(map.get("thisWeekNewMember").toString());
		Integer thisMonthNewMember= Integer.parseInt(map.get("thisMonthNewMember").toString());
		Integer todayOrderNumber= Integer.parseInt(map.get("todayOrderNumber").toString());
		Integer thisWeekOrderNumber= Integer.parseInt(map.get("thisWeekOrderNumber").toString());
		Integer thisMonthOrderNumber= Integer.parseInt(map.get("thisMonthOrderNumber").toString());
		Integer todayVisitsNumber= Integer.parseInt(map.get("todayVisitsNumber").toString());
		Integer thisWeekVisitsNumber= Integer.parseInt(map.get("thisWeekVisitsNumber").toString());
		Integer thisMonthVisitsNumber= Integer.parseInt(map.get("thisMonthVisitsNumber").toString());
		List<Map> hotSetmeal=(List)map.get("hotSetmeal");


		// 引入魔板
		String path = request.getSession()
				.getServletContext()
				.getRealPath("template")+ File.separator+ "report_template.xlsx";
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
		try {
			xssfWorkbook = new XSSFWorkbook(new FileInputStream(path));



		// 设置数据
		// 获取第一个标签页
		XSSFSheet sheet = xssfWorkbook.getSheetAt(0);

		XSSFRow row = sheet.getRow(2);
		row.getCell(5).setCellValue(reportDate);

		row = sheet.getRow(4);
		row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
		row.getCell(7).setCellValue(totalMember);//总会员数

		row = sheet.getRow(5);
		row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
		row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

		row = sheet.getRow(7);
		row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
		row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

		row = sheet.getRow(8);
		row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
		row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

		row = sheet.getRow(9);
		row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
		row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数


		//hotSetmeal.forEach(item->{
		//	row.getCell(4).setCellValue(item.get("name").toString());
		//
		//
		//});
		int num = 12;
		for (Map item : hotSetmeal) {
			row = sheet.getRow(num++);
			row.getCell(4).setCellValue(item.get("name").toString());
			row.getCell(5).setCellValue(Integer.parseInt(item.get("setmeal_count").toString()));
			row.getCell(6).setCellValue(new BigDecimal(item.get("proportion").toString()).doubleValue());
		}

		// 导出文件
		ServletOutputStream outputStream = response.getOutputStream();
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

		xssfWorkbook.write(outputStream);
		outputStream.flush();
		outputStream.close();
		xssfWorkbook.close();



		} catch (IOException e) {
			e.printStackTrace();
			return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
		}


		return null;
	}


	public static void main(String[] args) {
		LocalDate startDate = LocalDate.now().minusMonths(12);
		List<String> months = new ArrayList();
		for (int i = 0; i < 12 ; i++) {
			LocalDate tempDate = startDate.plusMonths(i);
			String s = tempDate.toString().substring(0, 7);
			months.add(s);

		}

		months.forEach(month->{
			System.out.println(month);
		});
	}
}
